package com.huluobo.a2203kotlinjetpackdemo.livedata

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel

/**
 *  Created by LC on 2024/7/18.
 */
class StudentViewModel : ViewModel() {
    private val studentLiveData = MutableLiveData<Student>()

    fun setStudentInfo(student: Student) {
        studentLiveData.value = student
    }

    //普通的get方法,方便理解
    fun getStudent() = studentLiveData

    //作为一个属性来写了一个get方法,本质上和普通的get方法没有任何区别
    val _student: LiveData<Int>
        //修改观测对象,因为一个学生类中id和名字是不会发生改变的,发生改变的只有分数,所以我们只需要观测分数即可
        get() = Transformations.map(studentLiveData) {
            it.score
        }

    //一个商品类
    data class Goods(val price: Double, val desc: String, val count: Int)

    //通过map转化总价的例子
    //商品的LiveData
    val goodsListLiveData: LiveData<List<Goods>> = MutableLiveData(
        listOf(
            Goods(100.0, "粉笔", 1),
            Goods(200.0, "粉笔擦", 2)
        )
    )

    //总价的LiveData
    val totalPriceLiveData: LiveData<Double> = Transformations.map(goodsListLiveData) {
        it.sumOf { goods ->
            goods.price * goods.count
        }
    }
}